package com.tianyadu.mmall.core.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 短信验证码安全认证
 *
 * @author xueyj
 * @date 2019-11-14 22:36
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    /**
     * 用户详情获取
     */
    private UserDetailsService userDetailsService;

    /**
     * 安全认证
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取用户手机号token信息
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        //  通过用户手机号查找用户信息
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        //  校验用户信息是否为空
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        //  认证成功，获取用户认证信息
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());
        //  重置用户认证token信息（是否认证，用户基本信息等）
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    /**
     * 校验当前认证类型是否有效，需将自定义认证方式添加至安全认证框架中
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#
     * supports(java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> authentication) {
        //  校验当前传递认证方式是否为SmsCodeAuthenticationToken
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}